import 'package:flutter/material.dart';
// import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
// import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:rjpb/page/home/inspection/controller/inspection_page_controller.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:rjpb/page/home/inspection/controller/chart_controller.dart';
import 'package:get/get.dart';
import 'package:rjpb/page/home/inspection/widgets/IndpectionListItem.dart';
import 'package:rjpb/page/home/inspection/widgets/menu_svg_view.dart';
import 'package:rjpb/components/z_icons/z_empty.dart';

import 'package:flutter_svg/flutter_svg.dart';
import 'package:rjpb/shared/extensions/extensions.dart';
import 'package:rjpb/components/gap.dart';

class InspectionPage extends StatefulWidget {
  @override
  _InspectionPage createState() => _InspectionPage();
}

class _InspectionPage extends State<InspectionPage> {
  final InspectionPageController _InspectionPageController =
      Get.put(InspectionPageController());
  final ChartController _chartController = Get.put(ChartController());

  @override
  void initState() {
    super.initState();
    _InspectionPageController.loadInitialData();
    // 加载菜单数据
    // _InspectionPageController.loadMenuData();
    _InspectionPageController.loadMenuData().then((_) {
      // 默认选中第一个菜单项并更新饼图数据
      if (_InspectionPageController.menuData.isNotEmpty) {
        // final defaultMenuId = _InspectionPageController.menuData.first['id'];
        // _InspectionPageController.onMenuItemSelected(defaultMenuId);
        final menuWithoutChildren =
            _InspectionPageController.menuData.firstWhere(
          (menu) => menu['children'] == null || menu['children'].isEmpty,
          orElse: () => <String, dynamic>{}, // 返回一个空的 Map
        );

        if (menuWithoutChildren.isNotEmpty) {
          final defaultMenuId = menuWithoutChildren['id'];
          _InspectionPageController.onMenuItemSelected(defaultMenuId);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            // 左侧 UI
            Expanded(
              flex: 2,
              child: Column(
                children: [
                  Container(
                    height: 200, // 固定高度
                    child: Obx(() {
                      return Echarts(
                        option: '''
      {
        title: {
          text: '${_chartController.totalPoints.value}',
          subtext: '点位总数',
          left: '43%',
          top: '51%',
          textAlign: 'center', // 确保数值水平居中
          subtextAlign: 'center', // 确保点位总数水平居中
          textStyle: {
            fontSize: 20, // 调整数字大小
            fontWeight: 'bold',
            color: '#333',
            align: 'center' // 确保文字水平居中
          },
          subtextStyle: {
            color: '#666',
            fontSize: 12, // 调整子标题大小
            align: 'center' // 确保子标题水平居中
          },
          itemGap: 2 // 调整数字和子标题之间的间距为 0
        },
        legend: {
          orient: 'vertical', // 图例垂直排列
          right: 0, // 图例靠右
          top: 0, // 图例靠上
          textStyle: {
            fontSize: 10, // 图例文字大小
            rich: {
              value: {
                color: '#18355C',
                  fontSize: 14,
                    fontWeight: 'bold',
              },
              percent: {
                color: '#847777e0',
                    fontWeight: 'bold',
              },
              bracket: {
                color: '#847777e0',
                fontWeight: 'bold'
              }
            }
          },
          itemWidth: 8, // 图例圆圈宽度（控制大小）
          itemHeight: 8, // 图例圆圈高度（控制大小）
          formatter: function(name) {
            const total = ${_chartController.totalPoints.value};
            const data = {
              '正常': { value: ${_chartController.normalCount.value}, percent: total === 0 ? '0.00' : (${_chartController.normalCount.value} / total * 100).toFixed(2) },
              '异常': { value: ${_chartController.abnormalCount.value}, percent: total === 0 ? '0.00' : (${_chartController.abnormalCount.value} / total * 100).toFixed(2) },
              '未检': { value: ${_chartController.uncheckedCount.value}, percent: total === 0 ? '0.00' : (${_chartController.uncheckedCount.value} / total * 100).toFixed(2) }
            };
            return name + '：{value|' + data[name].value + '} {bracket|(}{percent|' + data[name].percent + '%}{bracket|)}';
          },
          icon: 'circle' // 图例形状为点
        },
        series: [
          {
            type: 'pie',
            radius: ['44%', '58%'], // 调整饼图大小
            center: ['45%', '65%'], // 调整饼图位置（偏左）
            selectedMode: 'single', // 确保启用单选模式
            avoidLabelOverlap: false,
            label: {
              show: false // 隐藏指示文字
            },
            labelLine: {
              show: false // 隐藏指示线
            },
            data: [
              {value: ${_chartController.normalCount.value}, name: '正常', itemStyle: {color: '#00D488'}}, // 正常区域为绿色
              {
                value: ${_chartController.abnormalCount.value},
                name: '异常',
                itemStyle: {color: '#FF0000'},
                selected: true,
              },
              {value: ${_chartController.uncheckedCount.value}, name: '未检', itemStyle: {color: '#FFA800'}} // 未巡检区域为灰色
            ]
          }
        ]
      }
      ''',
                      );
                    }),
                  ),
                  SizedBox(height: 16),
                  Expanded(
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black12,
                            blurRadius: 5,
                            spreadRadius: 2,
                          ),
                        ],
                      ),
                      child: Obx(() {
                        final rows = _InspectionPageController.rows;
                        if (_InspectionPageController.empty.value) {
                          return LayoutBuilder(
                            builder: (context, constraints) {
                              return ZEmpty(
                                gapH: 0,
                                width: constraints.maxWidth, // 父容器的最大宽度
                                height: constraints.maxHeight, // 父容器的最大高度
                              );
                            },
                          );
                        }

                        return NotificationListener<ScrollNotification>(
                          onNotification: (scrollNotification) {
                            if (scrollNotification is ScrollEndNotification &&
                                scrollNotification.metrics.pixels ==
                                    scrollNotification
                                        .metrics.maxScrollExtent) {
                              _InspectionPageController.loadMoreData();
                            }
                            return false;
                          },
                          child: ListView.builder(
                            padding: const EdgeInsets.all(10.0),
                            itemCount: rows.length,
                            itemBuilder: (context, index) {
                              final row = rows[index];
                              final userNames =
                                  (row['userName'] as List<dynamic>)
                                      .map((user) => user['nickName'])
                                      .join('、');
                              // final additionalInfo = {
                              //   // 动态 key:value 数据
                              //   '其他信息1': row['otherInfo1'] ?? '无',
                              //   '其他信息2': row['otherInfo2'] ?? '无',
                              // };

                              return InspectionListItem(
                                periodSchemeStatus:
                                    row['periodSchemeStatus'] ?? '未知',
                                periodSchemeName:
                                    row['periodSchemeName'] ?? '未知任务',
                                periodFrequency:
                                    '${row['periodSchemeStartDate'] ?? '未知'} - ${row['periodSchemePeriodDate'] ?? '未知'}',
                                tlName: row['tlName'] ?? '未知',
                                userNames:
                                    userNames.isNotEmpty ? userNames : '暂无',
                                // additionalInfo: additionalInfo,
                                onTap: () {
                                  _InspectionPageController.onListItemTap(
                                      index);
                                },
                              );
                            },
                          ),
                        );
                      }),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: 16),
            // 中间新增列

            Expanded(
              flex: 7,
              child: Obx(() {
                // 监听菜单数据加载状态
                if (_InspectionPageController.isLoading.value) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                }

                // if (_InspectionPageController.menuData.isEmpty) {
                //   return Center(
                //     child: Text(
                //       '暂无菜单数据',
                //       style: TextStyle(fontSize: 16, color: Colors.black54),
                //     ),
                //   );
                // }

                return MenuSvgLayout(
                  menuData: _InspectionPageController.menuData,
                  onMenuItemSelected: (id) {
                    // 处理菜单项选中逻辑
                    _InspectionPageController.onMenuItemSelected(id);
                  },
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}
